package com.sunther.document.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sunther.document.entity.RoleEntity;
import com.sunther.document.entity.RoleTagEntity;
import com.sunther.document.service.RoleService;
import com.sunther.document.util.UserInfoUtil;
import com.sunther.idb.common.util.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * @author csb
 * @description: TODO
 * @date 2023/5/6 16:28
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/list")
    public WebResult list(@RequestParam(required = false) String keyword) {
        try {
            return WebResult.success("操作成功",roleService.listByKeyword(keyword));
        }catch (Exception e) {
            return WebResult.failure("操作失败");
        }
    }

    @GetMapping("/detail")
    public WebResult listAndRoleTag(@RequestParam Integer roleId) {
        try {
            return roleService.detail(roleId);
        }catch (Exception e) {
            return WebResult.failure("操作失败");
        }
    }

    @GetMapping("/list_and_tag")
    public WebResult listAndRoleTag() {
        try {
            return WebResult.success("操作成功",roleService.listAndRoleTag());
        }catch (Exception e) {
            return WebResult.failure("操作失败");
        }
    }

    @PostMapping("/saveByIds")
    public WebResult saveByIds(@RequestParam(name = "tagIds") String tagIds ,@RequestParam(name = "roleId") Integer roleId){
        try {
            Gson gson = new Gson();
            Set<Integer> ids = gson.fromJson(tagIds, new TypeToken<Set<Integer>>() {}.getType());
            return roleService.saveByIds(ids,roleId);
        }catch (Exception e) {
            return WebResult.failure("操作失败");
        }
    }

    @PostMapping("/save")
    public WebResult save(@RequestBody RoleEntity data){
        try {
            return roleService.saveData(data);
        }catch (Exception e) {
            return WebResult.failure("操作失败");
        }
    }

    @GetMapping("/getMenu")
    public WebResult getMenu(HttpServletRequest request){
        try {
            Integer roleId = UserInfoUtil.getRoleId(request);
            return roleService.getMenu(roleId);
        }catch (Exception e) {
            return WebResult.failure("操作失败");
        }
    }
}
